package com.hbx.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * @Author:hbx
 * 
 * 特殊字符验证
 * */
public class SpecicalUtil {
    /**
     *  特殊字符
     */
    private static final String SPECIAL_CHAR_REGEX = "[`~!@#$%^&*()_\\-+=<>?:\"{}|,.\\/;'\\[\\]·~！@#￥%……&*（）——+={}|《》？：“”【】、；‘'，。、]";
    /**
     *  汉字
     */
    private static final String CHINESE_REGEX = "[\u4e00-\u9fa5]";

    private static final Integer CHINESE_NUM = 2;

    /**
     * 过滤特殊字符
     * @param str
     * @return
     */
    public static String charFilter(String str){
        String result = null;
        if (str == null){
            return result;
        }

        try {
            Pattern p = Pattern.compile(SPECIAL_CHAR_REGEX);
            Matcher m = p.matcher(str);
            result = m.replaceAll("").trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 获取str的字符个数
     * @param str
     * @param num 一个汉字占几个字符
     * @return
     */
    public static Integer getStrCharCount(String str,Integer num){
        Integer count = 0;
        String filterResult = charFilter(str);
        if (filterResult == null){
            return count;
        }
        Pattern p = Pattern.compile(CHINESE_REGEX);
        Matcher m = p.matcher(filterResult);
        while (m.find()){
            count++;
        }
        return filterResult.toCharArray().length - count + count * num;
    }

    /**
     * 获取str的字符个数
     * @param str
     * @return
     */
    public static Integer getStrCharCount(String str){
        return getStrCharCount(str,CHINESE_NUM);
    }
}
